
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;

import enigma.console.Console;

public class DisplayStream {

	PriorityQueue<RadioPacket> queue = new PriorityQueue<RadioPacket>();
	//Stack<RadioPacket> queue = new Stack<RadioPacket>();
	private Console client;
	private Timer timer=new Timer();
	private int delay = 0;
	private int interval = 0;
	int lastIdReceived = 0;
	int lastIdPrinted = 0;
	
	public void setDelay(int delay)
	{
		this.delay = delay;
	}
	public void setInterval(int interval)
	{
		this.interval = interval;
	}
	public DisplayStream(Console client) {
		this.client = client;
	}
	public void start(){
		timer.schedule(new TimerTask(){
			@Override
			public void run()
			{
				if(queue.size()>0){
					RadioPacket p = queue.poll();
					if(p==null){
						client.getOutputStream().println("Nothing in the buffer");
					}else{
						if(p.getPacketType().equals("MIS")){
							client.getOutputStream().println("------------------------------");
						}else{
							client.getOutputStream().println(p.getData());
							lastIdPrinted = new Integer(p.getPacketId());
						}
					}
				}
					
				
			}
		}, delay,interval);
	}
	public void queueData(RadioPacket data){
		
		//System.out.println(new Integer(data.getPacketId())-lastIdPrinted);
		if(new Integer(data.getPacketId())>lastIdPrinted){
			if(new Integer(data.getPacketId())-lastIdReceived!=1){
				RadioPacket p = new RadioPacket(100);
				p.setPacketType("MIS".getBytes());
				p.setPacketId((""+(new Integer(data.getPacketId())-1)).getBytes());
				queue.offer(p);
			}
			if(queue.contains(data)){
				System.out.println(queue.remove(data));
			}
			queue.offer(data);
			lastIdReceived = new Integer(data.getPacketId());
		}
	}
	
}